import { MessageContextType, type ErrorMessageContext } from '@onlook/models';
import { Icons } from '@onlook/ui/icons';
import { wrapXml } from '../../prompt/helpers';
import { BaseContext } from '../models/base';

export class ErrorContext extends BaseContext {
    static readonly contextType = MessageContextType.ERROR;
    static readonly displayName = 'Error';
    static readonly icon = Icons.InfoCircled;

    private static readonly errorsContentPrefix = `You are helping debug a Next.js React app, likely being set up for the first time. Common issues:
- Missing dependencies ("command not found" errors) → Suggest "bun install" to install the dependencies for the first time (this project uses Bun, not npm)
- Missing closing tags in JSX/TSX files. Make sure all the tags are closed.

The errors can be from terminal or browser and might have the same root cause. Analyze all the messages before suggesting solutions. If there is no solution, don't suggest a fix.
If the same error is being reported multiple times, the previous fix did not work. Try a different approach.

IMPORTANT: This project uses Bun as the package manager. Always use Bun commands:
- Use "bun install" instead of "npm install"
- Use "bun add" instead of "npm install <package>"
- Use "bun run" instead of "npm run"
- Use "bunx" instead of "npx"

NEVER SUGGEST THE "bun run dev" command. Assume the user is already running the app.`;

    static getPrompt(context: ErrorMessageContext): string {
        const branchDisplay = ErrorContext.getBranchContent(context.branchId);
        const errorDisplay = wrapXml('error', context.content);
        return `${branchDisplay}\n${errorDisplay}\n`;
    }

    static getLabel(context: ErrorMessageContext): string {
        return context.displayName || 'Error';
    }

    /**
     * Generate multiple errors content 
     */
    static getErrorsContent(errors: ErrorMessageContext[]): string {
        if (errors.length === 0) {
            return '';
        }
        let prompt = `${ErrorContext.errorsContentPrefix}\n`;
        for (const error of errors) {
            prompt += ErrorContext.getPrompt(error);
        }

        prompt = wrapXml('errors', prompt);
        return prompt;
    }

    private static getBranchContent(id: string): string {
        return wrapXml('branch', `id: "${id}"`);
    }
}